#!/usr/bin/env php
<?php

require_once 'vendor/autoload.php';


function copyTagsId3v2ToId3v1($filePath): void
{
    // 创建getID3对象
    $getID3 = new getID3;
    $fileInfo = $getID3->analyze($filePath);

    // 检查分析是否成功
    if ($fileInfo === false) {
        echo "无法分析文件: {$filePath}\n";
        return;
    }

    // 获取ID3v2标签数据
    $tagsV2 = $fileInfo['tags']['id3v2'];

    if (!empty($tagsV2)) {
        $tagsV1=[];
        foreach ($tagsV2 as $tag => $value) {
            if ($tag == 'genre') {
                $value = [255];
            } else {
                foreach ($value as $k => $v) {

                    if (is_numeric($v)) {
                        $v = intval($v);
                    } elseif (is_string($v)) {
                        $v = mb_convert_encoding($v, 'ISO-8859-1', 'UTF-8');
                    }
                    $value[$k] = $v;
                }
            }

            $tagsV1[$tag] = $value;
        }
        // 写入标签
        $tagWriter = new getid3_writetags();
        $tagWriter->filename = $filePath;
        $tagWriter->tagformats = array('id3v1'); // 或者使用'id3v1'来写入ID3v1标签
        $tagWriter->overwrite_tags = true; // 覆盖原有标签
        $tagWriter->tag_data = $tagsV1; // 设置新的标签数据

// 执行写入操作
        if (!$tagWriter->WriteTags()) {
            echo "写入标签失败: " . implode(', ', $tagWriter->errors). "\n";
        } else {
            echo "ID3v2标签已复制到ID3v1并保存至文件: {$filePath}\n";
        }


    }else {
        echo "文件: {$filePath} 没有ID3v2标签\n";
    }
    // 准备ID3v1标签数据，注意ID3v1的限制

}

function needsRecursiveProcessing($dirPath): bool
{
    // 检查目录下是否有子目录，决定是否需要递归处理
    $dir = new DirectoryIterator($dirPath);
    foreach ($dir as $item) {
        if ($item->isDot()) continue; // 忽略 . 和 ..
        if ($item->isDir()) return true;
    }
    return false;
}

function processDirectory($dirPath): void
{
    // 判断是否需要递归处理
    $recursive = needsRecursiveProcessing($dirPath);

    // 初始化目录迭代器
    $dirIterator = new RecursiveDirectoryIterator($dirPath, RecursiveDirectoryIterator::SKIP_DOTS);

    // 根据是否需要递归选择迭代方式
    $iterator = $recursive
        ? new RecursiveIteratorIterator($dirIterator, RecursiveIteratorIterator::SELF_FIRST)
        : new IteratorIterator($dirIterator);

    // 遍历目录
    foreach ($iterator as $file) {
        if ($file->isFile() && strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'mp3') {
            copyTagsId3v2ToId3v1($file->getPathname());
        }
    }
}


// 示例用法
$directory = realpath($argv[1]);

if ($directory === false) {
    echo "错误: 指定的路径不存在。\n";
    exit(1);
}


if (!is_dir($directory)) {
    echo "错误: 指定的路径不是一个有效的目录。\n";
    exit(1);
}


processDirectory($directory);





